<template>
    <view class="good_coupon_list" v-if="ispup">
        <view class="good_coupon_list_container">
            <view class="header">领取优惠券</view>
            <scroll-view
                scroll-top="scrollTop"
                scroll-y="true"
                class="scroll"
                @scrolltoupper="upper"
                @scrolltolower="lower"
                :show-scrollbar="fasle"
                @scroll="scroll">
                <coupon v-for="item in listData" :midWidth="402" :fontSize="10" :key="item.id" :Data="item">
                    <template #right>
                        <view class="dash" v-if="item.hasAcquired"> &nbsp;已领取 </view>
                        <view class="dash" v-else @click="acquireCouponHandler(item)"> {{ item.btnName }} </view>
                    </template>
                </coupon>
            </scroll-view>
            <view v-if="!listData.length" class="none">
                <img class="empty" :src="getImgOssUrl('/ui-prod-2.0.0/empty_coupon_2.0.png')" alt="" />
                <view class="title">暂无优惠券</view>
            </view>
            <view class="botton_block">
                <view class="botton" @click="closeHanlder">关闭</view>
            </view>
        </view>
    </view>
</template>
<script setup>
import coupon from '@/components/coupon';
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue';
import storage from '@/commons/storage';
import request from '@/request';
import { getImgOssUrl } from '@/commons/utils';
import { useTrace } from '@/commons/trace';
import subscribe from '@/commons/subscribe';

const { traceLoad, traceReport } = useTrace();
const props = defineProps(['goodsId', 'show']);
const emit = defineEmits(['close', 'popup']);
let totalCount = ref(0);
let listData = reactive([]);
let ispup = ref(false);
const getCouponList = async () => {
    try {
        let res = await request('queryGoodCouponListServ', {
            goodsId: props.goodsId,
            userId: storage.get('userId') || 0,
            shopId: storage.get('ZW_SHOP_ID'),
            pageSize: 99,
            pageNum: 1
        });
        totalCount.value = res.data.totalCount;
        if (res.data.list?.length) {
            listData.length = 0;
            res.data.list.map(x => {
                const e = {
                    id: x.id,
                    couponType: x.couponType,
                    couponDiscount: x.couponDiscountContent,
                    couponDiscountMost: x.couponDiscountMost || 0,
                    couponTitle: x.couponTitle,
                    couponTimeType: x.couponTimeType,
                    couponTimeStart: (x.couponTimeStart || ' ').split(' ')[0].replaceAll('-', '.'),
                    couponTimeEnd: (x.couponTimeEnd || ' ').split(' ')[0].replaceAll('-', '.'),
                    couponTimeValue: x.couponTimeValue,
                    couponMatch: x.couponMatch,
                    couponDescription: x.couponDescription,
                    couponPrerequisites: x.couponPrerequisites,
                    couponPrerequisitesAdditional: x.couponPrerequisitesAdditional,
                    isAcquired: x.isAcquired,
                    couponAcquiredThreshold: x.couponAcquiredThreshold,
                    btnName: x.couponAcquiredThreshold ? '领取已达上限' : '立即领取'
                };
                listData.push(e);
            });
        }
        ispup.value = true;
        emit('popup');
    } catch (error) {
        emit('close');
    }
};

const acquireCouponHandler = async val => {
    if (val.couponAcquiredThreshold) {
        return;
    }
    let res;
    try {
        res = await request('acquireCouponServ', {
            couponId: val.id
        });
    } catch (e) {
        uni.showToast({
            title: e.data.msg || '网络错误，请稍后重试~',
            icon: 'none'
        });
        return;
    }
    if (res.data) {
        traceReport('receive_coupon', { couponId: val.id, couponName: val.couponTitle });
        uni.showToast({
            title: '领取优惠券成功'
        });
        val.hasAcquired = true;
        await subscribe('getcoupon');
    }
};

const closeHanlder = () => {
    emit('close');
};

onMounted(() => {});

watch(
    () => props.show,
    val => {
        if (val) {
            traceLoad('visit_page_coupon');
            getCouponList();
        } else {
            ispup.value = false;
        }
    }
);
</script>
<style lang="scss" scoped>
.good_coupon_list {
    .header {
        text-align: center;
        font-size: 31rpx;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #fe292b;
        line-height: 100rpx;
        height: 100rpx;
    }
    .good_coupon_list_container {
        padding: 0 29rpx;
        // 80+30+30-29
        padding-bottom: 111rpx;
        min-height: 20vh;
        position: relative;
        .scroll {
            max-height: 60vh;
            margin-bottom: var(--safe-area-inset-bottom);
        }
        .dash {
            // 167-29-29 = 109
            height: 109rpx;
            font-size: 29rpx;
            border-left: 2rpx dashed #fcaaab;
            display: flex;
            align-items: center;
            padding: 0 0 0 12rpx;
            width: 200rpx;
            justify-content: center;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #fe292b;
        }
        .botton_block {
            bottom: 0;
            position: absolute;
            width: 100%;
            background: #ffffff;
            padding: 30rpx 0;
            padding-bottom: calc(24rpx + var(--safe-area-inset-bottom));
        }
        .botton {
            width: 690rpx;
            height: 80rpx;
            background: #fe292b;
            border-radius: 40rpx;
            line-height: 80rpx;
            text-align: center;
            font-size: 29rpx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #ffffff;
        }
    }
    .none {
        margin: 150rpx auto 250rpx;
        width: 290rpx;
        height: 256rpx;
        text-align: center;
        .empty {
            width: 100%;
            height: 100%;
        }
        .title {
            height: 40px;
            font-size: 29rpx;
            color: #333333;
            line-height: 40px;
        }
    }
}
</style>
